package com.jn.gsondemo.views;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jn.gsondemo.R;
import com.jn.gsondemo.entity.Book;

public class BookDetailActivity extends AppCompatActivity {
    private TextView titleTextView;
    private TextView catalogTextView;
    private TextView tagsTextView;
    private TextView sub1TextView;
    private TextView sub2TextView;
    private TextView readingTextView;
    private TextView onlineTextView;
    private TextView bytimeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);

        // 初始化TextView
        titleTextView = findViewById(R.id.title);
        catalogTextView = findViewById(R.id.catalog);
        tagsTextView = findViewById(R.id.tags);
        sub1TextView = findViewById(R.id.sub1);
        sub2TextView = findViewById(R.id.sub2);
        readingTextView = findViewById(R.id.reading);
        onlineTextView = findViewById(R.id.online);
        bytimeTextView = findViewById(R.id.bytime);

        // 读取JSON字符串
        String jsonString = getJsonString();

        // 解析JSON
        Book book = parseJson(jsonString);

        // 将数据绑定到界面
        titleTextView.setText(book.getTitle());
        catalogTextView.setText(book.getCatalog());
        tagsTextView.setText(book.getTags());
        sub1TextView.setText(book.getSub1());
        sub2TextView.setText(book.getSub2());
        readingTextView.setText(book.getReading());
        onlineTextView.setText(book.getOnline());
        bytimeTextView.setText(book.getBytime());
    }

    private String getJsonString() {
        // 这里应该是从assets文件夹读取book.json文件
        // 为了简化示例，这里直接使用硬编码的JSON字符串
        return "{ \"resultcode\": \"200\", \"reason\": \"Success\", \"result\": { \"data\": { \"title\": \"向诸葛亮借智慧\", \"catalog\": \"历史 心理学 管理 \", \"tags\": \"一本好书 三国历史 社会学好书推荐 管理书籍推荐 诸葛亮 \", \"sub1\": \"《向诸葛亮借智慧》\", \"sub2\": \"《向诸葛亮借智慧》是中央电视台《百家讲坛》主讲人赵玉平老师编著的一 本管理学类图书。\", \"img\": \"http://apis.juhe.cn/goodbook/img/379cdafe13f92d62e99388182a6d08ec.jpg\", \"reading\": \"8091人阅读\", \"online\": \"京东商城:http://book.jd.com/10483893.html 当当网:http://product.dangdang.com/product.aspx?product_id=21020821 苏宁易购:http://www.suning.com/emall/prd_10052_22001_-7_1006212_.html \", \"bytime\": \"2013年4月28日\" }, \"totalNum\": \"9\", \"pn\": 0, \"rn\": \"1\" } }";
    }

    private Book parseJson(String jsonString) {
        Gson gson = new Gson();
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
        JsonObject resultObject = jsonObject.getAsJsonObject("result");
        JsonObject dataObject = resultObject.getAsJsonObject("data");
        return gson.fromJson(dataObject, Book.class);
    }
}